package edu.ccut.saturn.basecomponent.database.impl.hsql.handler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.basecomponent.database.impl.AbstractSQLHandler;
import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.component.SaturnDataManager;

public class HsqlCountSQLHandler extends AbstractSQLHandler{

	public List<SaturnData> executeQuery(ISaturnSQL saturnSQL,
			Connection connection) throws SaturnComponentException {

		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = saturnSQL.getSql();
		List<SaturnData> list = new ArrayList<SaturnData>();
		int count=0;
		if (connection != null) {
			try {
				ps = connection.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
				debug("QUERY_SQL = " + sql);
				setConditionPrepareStatement(saturnSQL, 1, ps);
				rs = ps.executeQuery();
				ps.clearParameters();
				if(rs.next()){
					count = rs.getInt(1); 
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new SaturnComponentException("query count exception");
			} finally {
				if (rs != null) {
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
						throw new SaturnComponentException("ResultSet close exception");
					}
				}
				if (ps != null) {
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
						throw new SaturnComponentException("Statment close exception");
					}
				}
			}
		} else {
			throw new SaturnComponentException(
					"Can not get Connection in database component"); //$NON-NLS-1$
		}
		SaturnData saturnData= SaturnDataManager.getInstance().createData("http://edu.ccut.saturn.basecomponent/data::COUNT");
		saturnData.set("count", count);
		list.add(saturnData);
		return list;
	}
	
	@Override
	protected String getSpecialSqlKey(String typeKey) {
		if ("FLOAT".equalsIgnoreCase(typeKey)){
			typeKey = "DOUBLE";
		}
		if ("REAL".equalsIgnoreCase(typeKey)){
			typeKey = "DOUBLE";
		}
		return typeKey;
	}
	
	public int executeUpdate(ISaturnSQL saturnSQL, Connection connection)
			throws SaturnComponentException {
		return 0;
	}
}